package com.ly.mpayment.rest.up.anchang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("anchang")
public class AnChangRest {
    Logger logger = Logger.getLogger(AnChangRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("anchang_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject multiMap = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(multiMap.getString("orderNo"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            // 'userId' + 'memberId' + 'orderNo'+ 'upOrderNo'+ status + 客户密钥 + 子账户密钥;
            // if(!multiMap.getString("sign").equalsIgnoreCase(MD5.md5(
            //          upShopInfo.getAppId()+
            //              "&orderid="+multiMap.getString("orderid")+
            //              "&sporderid="+multiMap.getString("sporderid")+
            //              "&merchantsubmittime="+multiMap.getString("merchantsubmittime")+
            //              "&resultno="+multiMap.getString("resultno")+
            //              "&key="+upShopInfo.getUpkey()))){
            //     logger.info("签名错误:"+data);
            //     // return "failt";
            // }

            if (order != null && multiMap.getString("status").equals("0") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("thirdSeri") ? multiMap.getString("thirdSeri") :"");
                RechargeRest.successUpOrder.add(order);
                return "0000";
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("status").equals("4")) {
                order.setRemark(multiMap.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
                return "0000";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("msg"));
                logger.info("anchang_not_found_order:" + multiMap.getString("msg") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * . sign=MD5(参数 1 的值+参数 2 的值+参数 3 的值+….+ key1 + key2 )，其中
     * key1 为渠道客户秘钥，key2 为渠道客户的子账户密钥。
     * 4. sign 统一转换为大写
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        //主账户
        data.put("userId", shop.getAppId());
        data.put("memberId",shop.getUpshopip());
        data.put("reqTime", order.getCreatetime().getTime() / 1000 );
        data.put("prodType","HUAFEI");
        JSONObject orderInfo = new JSONObject();
        orderInfo.put("orderInfo","");
        data.put("orderInfo",orderInfo);
        orderInfo.put("orderNo",order.getUporderuuid());
        orderInfo.put("acctNo","HUAFEI");
        orderInfo.put("prodCode",order.getUpShopPro().getProductCode());
        orderInfo.put("reserve1","");
        orderInfo.put("reserve2","");
        data.put("sign", MD5.md5(shop.getAppId()+shop.getUpshopip()+data.getString("reqTime")+data.getString("prodType")
        +order.getUporderuuid()+shop.getUpkey()+"aee0228d726a6ef3912908a1f0068f46"));

        String result = HttpClient.post(shop.getOrderCommitAddress(), data.toString());
        logger.info("commitOrder_anchang:" + result + ":" +  (data));
        if (!StringUtils.isBlank(result)) {
            try{
                // 字段 类型 长度 描述
                // code string 4 错误码
                // msg string 1-80 错误描述
                // orderNo string 1-60 接入渠道订购订单号，原值返回
                // acctNo string 11 充值账号，原值返回
                // prodCode string 1-40 商品编码，原值返回
                // upOrderNo string 1-40 如果提交成功，返回平台侧的订单号
                JSONObject items = JSONObject.parseObject(result);
                logger.info("commitOrder_anchang_json:" + items);
                if (items.containsKey("code") && items.getString("code").equals("0000")) {
                    this.upOrderService.updateUpOrderMsg(order,items.getString("upOrderNo"),items.containsKey("msg") ?
                            items.getString("msg") : "");
                } else if (items.containsKey("code") && errorCode.contains(items.getString("code"))){
                    order.setRemark(items.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.updateUpOrderArtificial(order,"", items.getString("msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
*                 1001 账号异常
*                 1002 验签错误
*                 1003 号码对应的号段未配置
*                 1004 通道产品未配置
*                 1005 客户未配置号码所在省份的业务,请联系开通。
*                 1006 客户已关闭号码所在省份的业务,请联系开通。
*                 1007 产品非法/未配置
*                 1008 该号段不支持该产品。
*                 1009 产品已下架。
*                 1010 客户未配置该产品或客户产品未定价。
*                 1011 参数不全
*                 9999 其他错误:订单提交失败。
*                 2001 账户不存在或者配置错误
*                 2002 服务器限制接入
*                 3001 订单不存在
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("1001");
        add("1002");
        add("1003");
        add("1004");
        add("1005");
        add("1006");
        add("1007");
        add("1008");
        add("1009");
        add("1010");
        add("9999");
        add("1011");
        add("2001");
        add("2002");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("sporderid", upOrder.getUporderuuid());
        data.put("userId", shopInfo.getAppId());
        data.put("memberId",shopInfo.getUpshopip());
        data.put("reqTime",upOrder.getCreatetime().getTime() / 1000 );
        data.put("prodType","HUAFEI");
        JSONObject orderInfo = new JSONObject();
        orderInfo.put("orderNo",upOrder.getUporderuuid());
        // 'userId' + 'memberId' + 'reqTime'+ 'prodType'+ 'orderNo' + 客户密钥 + 子账户密钥;
        orderInfo.put("sign",shopInfo.getAppId() + shopInfo.getUpshopip()+data.getString("reqTime")+upOrder.getUporderuuid()+
                shopInfo.getUpkey()+"aee0228d726a6ef3912908a1f0068f46");
        data.put("orderInfo",orderInfo);
        String result = HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("anchangqueryOrder:" + data+ ":" + result);
        if (!StringUtils.isBlank(result)) {
            try {
                JSONObject items = JSONObject.parseObject(result);
                logger.info("queryOrder_anchang_json:" + items);

                if (items.containsKey("code") && items.getString("code").equals("0000") ) {
                    UpOrder order = upOrderService.findById(items.getString("orderNo"));
                    if (order != null && items.getString("status").equals("20") && order.getStatus() == Config.status[0]) {
                        order.setRemark( items.containsKey("thirdSeri") ? items.getString("thirdSeri") : "");
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] && items.getString("status").equals("4") ) {
                        order.setRemark(items.getString("msg"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,items.getString("msg"));
                        logger.info("anchang_not_found_order:" + order.getUpphonenum());
                    }
                } else {
                    logger.info("anchang_not_found_order:" + upOrder.getUpphonenum());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
